package ru.fsd.sokoban;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;


public class LevelLoader {
	
	private ArrayList<GameObject> objs = null;
	private GameBoard board = null;
	private BufferedReader buf = null;
	private Player player = null;
	
	public GameBoard loadBoard(String pathToFile) throws NumberFormatException, IOException {
		buf = new BufferedReader(new FileReader(new File(pathToFile)));
		
		int x = Integer.parseInt(buf.readLine());
		int y = Integer.parseInt(buf.readLine());
		board = new GameBoard(x, y);
		
		loadObjects();
		board.setObjs(objs);
		board.setPlayer(player);
		
		for(int i = 0; i < y; i++){
			for(int j = 0; j < x; j++) {
				board.setGameObject(parseObj(), j, i);
				if (j==x-1) {
					if ((char) buf.read() == '\r') buf.read();
				}
			}			
		}
		
		return board;
	}
	
	private GameObject parseObj() throws IOException {
		char ch = (char) buf.read();
		
		if(ch == ' ')
			return objs.get(GameObject.GROUND);
		else if(ch == 'X')
			return objs.get(GameObject.WALL);
		else if(ch == '*')
			return objs.get(GameObject.BOX);
		else if(ch == '.')
			return objs.get(GameObject.PLACE);
		else if(ch == '@')
			return objs.get(GameObject.PLAYER);
		else if(ch == '&')
			return objs.get(GameObject.BOX_ON_PLACE);
		else 
			return null;
	}
	
	private void loadObjects() throws IOException {
		objs = new ArrayList<GameObject>();
		player = new Player(ImageIO.read((new File("data/img/worker_right.png"))), ImageIO.read((new File("data/img/worker_left.png"))));
		
		objs.add(new GameObject(0, ImageIO.read((new File("data/img/ground.png")))));
		objs.add(new GameObject(1, ImageIO.read((new File("data/img/wall.png")))));
		objs.add(new GameObject(2, ImageIO.read((new File("data/img/box.png")))));
		objs.add(new GameObject(3, ImageIO.read((new File("data/img/place.png")))));
		objs.add(new GameObject(4, ImageIO.read((new File("data/img/box_on_place.png")))));
		objs.add(new GameObject(5, ImageIO.read((new File("data/img/worker_right.png")))));
	}
}
